package 分类.队列和栈;

public class 平衡括号字符串的最少插入次数 {
    public int minInsertions(String s) {
        int leftnum=0;
        int index=0;
        int res=0;
        while (index<s.length()){
            char c=s.charAt(index);
            if(c=='('){
                leftnum++;
                index++;
            }else {
                if(leftnum>0){
                    leftnum--;
                }else {
                    res++;
                }

                if(index<s.length()-1&&s.charAt(index+1)==')'){
                    index+=2;

                }else {
                    res++;
                    index+=1;
                }
            }
        }
        res+=leftnum*2;
        return res;
    }
}
